package com.UKIT.airtickets.Activities

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.UKIT.airtickets.Service.Handlers.Authenticator
import com.UKIT.airtickets.Service.Handlers.AuthenticatorCallbacks
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.databinding.AuthorizationBinding

class AuthorizationActivity : AppCompatActivity(), AuthenticatorCallbacks {

    private lateinit var binding: AuthorizationBinding
    private lateinit var authenticator: Authenticator

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AuthorizationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //Авто-авторизация в слючае хранения id пользователя в кеше
        val sharedPreferences = applicationContext.getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        if(sharedPreferences.getInt("user_id", 0) > 0) {
            SettingsApp.userId = sharedPreferences.getInt("user_id", 0).toLong()
            onAuthenticationSuccess()
        }

        authenticator = Authenticator(this, this)

        binding.authBtn.setOnClickListener {
            val login = binding.loginInput.text.toString()
            val password = binding.passwordInput.text.toString()
            authenticator.authenticate(login, password)
        }

        binding.ifNotAccount.setOnClickListener {
            goToRegistration()
        }
    }

    private fun showSuccessMessage() {
        runOnUiThread{
            Toast.makeText(this, "Успешная авторизация", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showFailureMessage() {
        runOnUiThread {
            Toast.makeText(this, "Неверный логин или пароль", Toast.LENGTH_SHORT).show()
        }
    }

    private fun goToMainActivity() {
        runOnUiThread {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    private fun goToRegistration() {
        runOnUiThread {
            val intent = Intent(this, RegistrationActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onAuthenticationSuccess() {
        showSuccessMessage()
        goToMainActivity()
    }

    override fun onAuthenticationFailure() {
        showFailureMessage()
    }
}